package com.ocom.common.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2023/5/31
 **/
public class ImageDownLoadUtils {

	public static String uploadImgByURL(String fileUrl,String savePath) {
		//获取文件名，文件名实际上在URL中可以找到
		String fileName = (fileUrl.split("/"))[fileUrl.split("/").length-1];
		try {
			URL url = new URL(fileUrl);/*将网络资源地址传给,即赋值给url*/
			/*此为联系获得网络资源的固定格式用法，以便后面的in变量获得url截取网络资源的输入流*/
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			DataInputStream in = new DataInputStream(connection.getInputStream());
			/*此处也可用BufferedInputStream与BufferedOutputStream*/
			DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(savePath+fileName)));
			/*将参数savePath，即将截取的图片的存储在本地地址赋值给out输出流所指定的地址*/
			byte[] buffer = new byte[4096];
			int count = 0;
			/*将输入流以字节的形式读取并写入buffer中*/
			while ((count = in.read(buffer)) > 0) {
				out.write(buffer, 0, count);
			}
			out.close();/*后面三行为关闭输入输出流以及网络资源的固定格式*/
			in.close();
			connection.disconnect();
			//返回内容是保存后的完整的URL
			return savePath+fileName;/*网络资源截取并存储本地成功返回true*/

		} catch (Exception e) {
			System.out.println(e + fileUrl + savePath);
			return null;
		}
	}

//	public static void main(String[] args) {
//		String upload = uploadImgByURL("https://up.enterdesk.com/edpic_source/b0/d1/f3/b0d1f35504e4106d48c84434f2298ada.jpg","E://test/");
//		System.out.println(upload);
//	}


	public static void main(String[] args) throws Exception {
		// URL of the image to download
		String imageUrl = "https://img2.woyaogexing.com/2023/05/31/a54b2b136d55c6b46574c295377e765a.jpg";

		// Create URL object and open input stream to the image
		URL url = new URL(imageUrl);
		InputStream inputStream = url.openStream();

		// Output stream to save the image to file
		FileOutputStream outputStream = new FileOutputStream("E://test1/image.jpg");

		// Read bytes from the input stream and write to the output stream
		byte[] buffer = new byte[2048];
		int length;
		while ((length = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, length);
		}

		// Close streams
		inputStream.close();
		outputStream.close();

		System.out.println("Image downloaded successfully.");
	}

}
